package com.itboye.mengwu.app.ui.mymeng;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.config.GlobalConfig;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseFragment;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.XImageLoader;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.ui.web.WebActivity;
import com.itboye.mengwu.buy.ui.DaiFuKuanDetail;
import com.itboye.mengwu.data.model.OrderBean;
import com.itboye.mengwu.data.model.OrderDetailBean;
import com.itboye.mengwu.data.model.OrderDetailBean.ItemsInfo;
import com.itboye.mengwu.data.model.OrderQueryModel;
import com.itboye.mengwu.data.presenter.OrderPresenter;
import com.itboye.mengwu.widget.XListView;
import com.itboye.mengwu.widget.XListView.IXListViewListener;

/***
 * 3待收货 order_status=2,待确认(已付款) order_status=3,待发货(已付款);
 * order_status=4,已发货待收货(已付款)】
 * 
 * @author admin
 * 
 */
public class FragmentDaiShouHuo extends BaseFragment implements Observer,
		IXListViewListener {
	XListView list_wait_get_goods;
	private OrderPresenter orderPresenter;
	private ArrayList<OrderQueryModel.OrderList> model = new ArrayList<OrderQueryModel.OrderList>();
	RelativeLayout re_nodata;
	private MyAdapter adapter;
	private int type;
	private OrderBean model2;
	private int pageNo = 1;
	protected String uid;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.list_wait_get_goods;
	}

	public FragmentDaiShouHuo(int type) {
		this.type = type;
	}

	@Override
	public void onMyActivityCreated() {
		uid = SPUtils.get(getActivity(), null, SpPublicParams.UID, "") + "";
		password=SPUtils.get(getActivity(), null, SpPublicParams.PASSWORD, "")+"";
		list_wait_get_goods = (XListView) (getActivity())
				.findViewById(R.id.get_goods_list);
		list_wait_get_goods.setXListViewListener(this);
		list_wait_get_goods.setPullLoadEnable(true);
		list_wait_get_goods.setPullRefreshEnable(true);
		showProgressDialog("加载中，请稍后", true);
		orderPresenter = new OrderPresenter(this);
		model2 = new OrderBean();
		model2.setPageNo(pageNo + "");
		model2.setUid(SPUtils.get(getActivity(), null, SpPublicParams.UID, "")
				+ "");
		model2.setStatus(3 + "");
		orderPresenter.getInfo(model2);
		list_wait_get_goods.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(), DaiFuKuanDetail.class);
				intent.putExtra("type", "3");
				intent.putExtra("id", model.get(position - 1).getId());
				Log.e("hu---", model.get(position - 1).getOrderCode());
				startActivity(intent);
			}
		});

	}

	protected String password;
	public class MyAdapter extends BaseAdapter {
		int resID;
		Context context;
		public MyAdapter(Context context, int resID) {
			this.context = context;
			this.resID = resID;
			
		}

		@Override
		public int getCount() {
			return model == null ? 0 : model.size();
		}

		@Override
		public Object getItem(int position) {
			return model.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder viewHolder = null;
			int totalCount = 0;
			if (viewHolder == null) {
				viewHolder = new Holder();
				convertView = CreateView();
				viewHolder.querenshouhuo = (Button) convertView
						.findViewById(R.id.querenshouhuo);
				viewHolder.wait_pay_tv = (TextView) convertView
						.findViewById(R.id.wait_pay_tv);
				viewHolder.tuikuan = (Button) convertView
						.findViewById(R.id.tuikuan);
				viewHolder.wuliu = (Button) convertView
						.findViewById(R.id.btn_1);
				viewHolder.yunfei = (TextView) convertView
						.findViewById(R.id.yunfei);
				viewHolder.total_num_tv = (TextView) convertView
						.findViewById(R.id.total_num_tv);
				viewHolder.goodsgroup = (LinearLayout) convertView
						.findViewById(R.id.goodsgroup);
				viewHolder.total_price = (TextView) convertView
						.findViewById(R.id.total_price);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (Holder) convertView.getTag();
			}
			viewHolder.wuliu.setTag(position);
			viewHolder.tuikuan.setTag(position);
			viewHolder.querenshouhuo.setTag(position);
			viewHolder.goodsgroup.removeAllViews();
			if (model.get(position).getItems() != null) {
				for (int i = 0; i < model.get(position).getItems().size(); i++) {
					View childView = LayoutInflater.from(getActivity())
							.inflate(R.layout.goods_item, null);
					((TextView) childView.findViewById(R.id.dangge_shuliang))
							.setText("x"
									+ model.get(position).getItems().get(i)
											.getCount());
					((TextView) childView.findViewById(R.id.goods_old_price))
							.setText("￥"
									+ model.get(position).getItems().get(i)
											.getOriPrice());
					((TextView) childView.findViewById(R.id.goods_old_price))
							.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); // 中划线
					XImageLoader.load(
							GlobalConfig.API_URL
									+ "/picture/index?id="
									+ model.get(position).getItems().get(i)
											.getImgUrl(),
							((ImageView) childView
									.findViewById(R.id.wait_pay_iv)));
					((TextView) childView.findViewById(R.id.goods_price))
							.setText("￥"
									+ model.get(position).getItems().get(i)
											.getPrice());
					((TextView) childView.findViewById(R.id.goodsname_tv))
							.setText(model.get(position).getItems().get(i)
									.getName());
					((TextView) childView.findViewById(R.id.buy_num))
							.setText(model.get(position).getItems().get(i)
									.getSkuDesc());
					totalCount += Integer.parseInt(model.get(position)
							.getItems().get(i).getCount());
					viewHolder.goodsgroup.addView(childView);
				}
			}
			if (model.get(position).getOrderStatus().equals("2")||model.get(position).getOrderStatus().equals("3")) {
				viewHolder.wait_pay_tv.setText("待发货");
				viewHolder.wuliu.setVisibility(View.GONE);
				viewHolder.tuikuan.setVisibility(View.GONE);
				viewHolder.querenshouhuo.setVisibility(View.VISIBLE);
				viewHolder.querenshouhuo.setText("申请售后");
				viewHolder.querenshouhuo.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(getActivity(),
								ActivityShenQingShouHou.class);
						OrderDetailBean bean = new OrderDetailBean();
						bean.setOrderCode(model.get((int) v.getTag())
								.getOrderCode());
						List<OrderDetailBean.ItemsInfo> info = new ArrayList<OrderDetailBean.ItemsInfo>();
						for (int j = 0; j < model.get((int) v.getTag()).getItems()
								.size(); j++) {
							ItemsInfo info2 = new ItemsInfo();
							info2.setCount(model.get((int) v.getTag()).getItems()
									.get(j).getCount());
							info2.setName(model.get((int) v.getTag()).getItems()
									.get(j).getName());
							info2.setPrice(model.get((int) v.getTag()).getItems()
									.get(j).getPrice());
							info2.setImg(model.get((int) v.getTag()).getItems()
									.get(j).getImgUrl());
							info.add(info2);
						}
						bean.setItems(info);
						intent.putExtra("model", bean);
						startActivity(intent);
					}
				});
			} else if (model.get(position).getOrderStatus().equals("4")) {
				viewHolder.wait_pay_tv.setText("待收货");
				viewHolder.tuikuan.setVisibility(View.VISIBLE);
//				viewHolder.tuikuan.setText("查看物流");
//				viewHolder.tuikuan.setOnClickListener(new OnClickListener() {
//					
//					@Override
//					public void onClick(View v) {
//						// TODO Auto-generated method stub
//						Intent intent = new Intent(getActivity(),
//								ActivityShenQingShouHou.class);
//						OrderDetailBean bean = new OrderDetailBean();
//						bean.setOrderCode(model.get((int) v.getTag())
//								.getOrderCode());
//						List<OrderDetailBean.ItemsInfo> info = new ArrayList<OrderDetailBean.ItemsInfo>();
//						for (int j = 0; j < model.get((int) v.getTag()).getItems()
//								.size(); j++) {
//							ItemsInfo info2 = new ItemsInfo();
//							info2.setCount(model.get((int) v.getTag()).getItems()
//									.get(j).getCount());
//							info2.setName(model.get((int) v.getTag()).getItems()
//									.get(j).getName());
//							info2.setPrice(model.get((int) v.getTag()).getItems()
//									.get(j).getPrice());
//							info2.setImg(model.get((int) v.getTag()).getItems()
//									.get(j).getImgUrl());
//							info.add(info2);
//						}
//						bean.setItems(info);
//						intent.putExtra("model", bean);
//						startActivity(intent);
//					}
//				});
				viewHolder.wuliu.setVisibility(View.VISIBLE);
				viewHolder.wuliu.setText("查看物流");
				viewHolder.wuliu.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(getActivity(),
								WebActivity.class);
						Log.v("url", GlobalConfig.API_URL+"/Express/ViewOrder?order_code="+model.get((int) v.getTag()).getOrderCode()+"&uid="+uid+"&psw="+password);
						intent.putExtra("title","物流查询");
						intent.putExtra("url","http://www.moodwo.com/index.php/Webview/Express/ViewOrder?order_code="+model.get((int) v.getTag()).getOrderCode()+"&uid="+uid+"&psw="+password);
						startActivity(intent);
					}
				});
				viewHolder.querenshouhuo.setVisibility(View.VISIBLE);
				viewHolder.querenshouhuo.setTag(position);
				viewHolder.querenshouhuo.setText("确认收货");
				viewHolder.querenshouhuo.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						orderPresenter.makesureOrder(uid, model.get((int) v.getTag()).getOrderCode());
					}
				});
				viewHolder.tuikuan.setText("申请售后");
				viewHolder.tuikuan.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(getActivity(),
								ActivityShenQingShouHou.class);
						OrderDetailBean bean = new OrderDetailBean();
						bean.setOrderCode(model.get((int) v.getTag())
								.getOrderCode());
						List<OrderDetailBean.ItemsInfo> info = new ArrayList<OrderDetailBean.ItemsInfo>();
						for (int j = 0; j < model.get((int) v.getTag()).getItems()
								.size(); j++) {
							ItemsInfo info2 = new ItemsInfo();
							info2.setCount(model.get((int) v.getTag()).getItems()
									.get(j).getCount());
							info2.setName(model.get((int) v.getTag()).getItems()
									.get(j).getName());
							info2.setPrice(model.get((int) v.getTag()).getItems()
									.get(j).getPrice());
							info2.setImg(model.get((int) v.getTag()).getItems()
									.get(j).getImgUrl());
							info.add(info2);
						}
						bean.setItems(info);
						intent.putExtra("model", bean);
						startActivity(intent);
					}
				});
			}
//			viewHolder.querenshouhuo.setTag(model.get(position).getOrderCode());
			// viewHolder.wait_pay_tv.setText(model.get(position).getOrderStatus()+"pay"+model.get(position).getPayStatus());
			viewHolder.total_num_tv.setText("共"
					+ totalCount + "件商品");
			

			
//			viewHolder.tuikuan.setVisibility(View.GONE);
//			viewHolder.wuliu.setVisibility(View.GONE);
			viewHolder.total_price
					.setText("￥"
							+ (Double.parseDouble(model.get(position)
									.getPrice())
									- Double.parseDouble(model.get(position)
											.getDiscountMoney()) + Double
										.parseDouble(model.get(position)
												.getPostPrice())) + "");
			viewHolder.yunfei.setText("(含运费￥"
					+ model.get(position).getPostPrice() + ")");
			viewHolder.tuikuan.setTag(position);
			return convertView;
		}

		// @SuppressLint("InflateParams")
		private View CreateView() {
			View v = null;
			LayoutInflater inflater = LayoutInflater.from(getActivity());
			v = inflater.inflate(R.layout.item_wait_get_goods, null);
			return v;
		}

		class Holder {
			private Button wuliu, querenshouhuo, tuikuan;
			TextView total_num_tv, goodsname_tv, buy_num, goods_price,
					total_price, yunfei, wait_pay_tv;
			LinearLayout goodsgroup;
			ImageView wait_pay_iv;
		}

	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == OrderPresenter.OrderQuerySuccess) {
				if (pageNo == 1)
					model.clear();
				model.addAll(((OrderQueryModel) entity.getData()).getList());
				adapter = new MyAdapter(getActivity(), R.layout.item_wait_pay);
				list_wait_get_goods.setAdapter(adapter);
			} else if (entity.getEventType() == OrderPresenter.OrderQueryFail) {

			} else if (entity.getEventType() == OrderPresenter.OrderSureSuccess) {
				ByAlert.alert(entity.getData() + "");
			} else if (entity.getEventType() == OrderPresenter.OrderSureFail) {
				ByAlert.alert(entity.getData() + "");
			}
		}
		stopLoad();
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		pageNo = 1;
		model2.setPageNo(pageNo + "");
		orderPresenter.getInfo(model2);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		pageNo++;
		model2.setPageNo(pageNo + "");
		orderPresenter.getInfo(model2);
	}

	public void stopLoad() {
		list_wait_get_goods.stopLoadMore();
		list_wait_get_goods.stopRefresh();
	}

}
